package com.building.hcrm.ui.customer;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.R.id;
import com.building.hcrm.R.layout;
import com.building.hcrm.R.string;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.base.BaseStaffSelector.SelectedStaffListener;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.common.Utils;
import com.building.hcrm.model.AttributionExamine;
import com.building.hcrm.model.CustomerAttribution;
import com.building.hcrm.model.CustomerDetail;
import com.building.hcrm.model.CustomerExamine;
import com.building.hcrm.model.ExamineQuery;
import com.building.hcrm.model.SysUser;
import com.building.hcrm.ui.customcontrols.ComStaffSelector;
import com.building.hcrm.wcf.CustomerServiceProxy;
import com.widget.time.JudgeDate;
import com.widget.time.ScreenInfo;
import com.widget.time.WheelMain;

public class CustomerActivityAudit extends BaseActivity {

	private WheelMain wheelMain;
	private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private ComStaffSelector mSelector;
	private RadioButton rbtnRecord;
	private RadioButton rbtnCustomer;
	private RadioButton rbtnStatusNot;
	private RadioButton rbtnStatusHavent;
	private RadioButton rbtnStatusDid;
	private Button btnStartTime;
	private Button btnEndTime;
	private LinearLayout linearSearch = null;
	private ListView listResult;
	private CustomerDetailAdapter mCustomerDetailAdapter;
	private AttributionAdapter mAttributionAdapter;
	private CustomerExamine mCustomerExamine;
	private AttributionExamine mAttributionExamine;

	private SysUser mSysUser = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customer_audit);
		initControls();
		initDatas();
		setOnAllListeners();
	}

	private void initControls() {
		mSelector = (ComStaffSelector) findViewById(R.id.staff_selector);
		rbtnRecord = (RadioButton) findViewById(R.id.rbtn_record);
		rbtnCustomer = (RadioButton) findViewById(R.id.rbtn_customer);
		rbtnStatusNot = (RadioButton) findViewById(R.id.rbtn_not);
		rbtnStatusHavent = (RadioButton) findViewById(R.id.rbtn_havent);
		rbtnStatusDid = (RadioButton) findViewById(R.id.rbtn_did);
		btnStartTime = (Button) findViewById(id.btn_start_time);
		btnEndTime = (Button) findViewById(id.btn_end_time);
		linearSearch = (LinearLayout) findViewById(id.linear_Search);
		listResult = (ListView) findViewById(id.list_search_result);
		imgbtnHome = (ImageButton) findViewById(id.imgbtn_home);
		imgbtnHome.setVisibility(View.VISIBLE);
	}

	private void initDatas() {
		setTitle(getResources().getString(string.audit_title));
		mSelector.load(ComStaffSelector.DISPLAY_TYPE_ALL,
				User.getInstance(CustomerActivityAudit.this));
		Calendar calendar = Calendar.getInstance();
		btnEndTime.setText(dateFormat.format(calendar.getTime()));
		calendar.add(calendar.DATE, -1);
		Date dateYesterday = calendar.getTime();
		btnStartTime.setText(dateFormat.format(dateYesterday));
	}

	private void setOnAllListeners() {
		mSelector.setOnSelectedStaffListener(new SelectedStaffListener() {
			@Override
			public void onSelectedStaff(SysUser inStaff) {
				if (null != inStaff) {
					mSysUser = mSelector.getCurrentStaff();
				}
			}
		});

		linearSearch.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {

					ExamineQuery examineQuery = new ExamineQuery();
					examineQuery.DateStart = dateFormat.parse(btnStartTime
							.getText().toString());
					examineQuery.DateEnd = dateFormat.parse(btnEndTime
							.getText().toString());
					if (examineQuery.DateStart.compareTo(examineQuery.DateEnd) == 1) {
						Toast.makeText(getApplicationContext(), "开始时间不能大于结束时间",
								Toast.LENGTH_SHORT).show();
						return;
					}
					examineQuery.CreateUser = mSysUser.getUserNum();
					if (rbtnStatusNot.isChecked()) {
						examineQuery.State = "0";
					} else if (rbtnStatusHavent.isChecked()) {
						examineQuery.State = "1";
					} else if (rbtnStatusDid.isChecked()) {
						examineQuery.State = "2";
					}
					examineQuery.DateStart = dateFormat.parse(btnStartTime
							.getText().toString());
					examineQuery.DateEnd = dateFormat.parse(btnEndTime
							.getText().toString());
					examineQuery.UserNum = User.getInstance(
							CustomerActivityAudit.this).getUserNum();
					if (rbtnCustomer.isChecked()) {
						SearchCustomerListTask task = new SearchCustomerListTask();
						task.execute(examineQuery);
					} else {
						SearchAttributionListTask task = new SearchAttributionListTask();
						task.execute(examineQuery);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		});

		setTimeClick(btnStartTime);
		setTimeClick(btnEndTime);

		imgbtnHome.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// getDatas();
				finish();
				slideReturnActivity();
			}
		});
	}

	private void setTimeClick(final Button btn) {
		btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater
						.from(CustomerActivityAudit.this);
				final View timepickerview = inflater.inflate(
						R.layout.item_time_picker, null);
				ScreenInfo screenInfo = new ScreenInfo(
						CustomerActivityAudit.this);
				wheelMain = new WheelMain(timepickerview);
				wheelMain.screenheight = screenInfo.getHeight();
				String time = btn.getText().toString();
				Calendar calendar = Calendar.getInstance();
				if (JudgeDate.isDate(time, "yyyy-MM-dd")) {
					try {
						calendar.setTime(dateFormat.parse(time));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH);
				int day = calendar.get(Calendar.DAY_OF_MONTH);
				wheelMain.initDateTimePicker(year, month, day);
				new AlertDialog.Builder(CustomerActivityAudit.this)
						.setTitle("时间选择")
						.setView(timepickerview)
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										btn.setText(wheelMain.getTime());
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).show();
			}
		});
	}

	/**
	 * 查询客户信息异步类
	 * 
	 * @author MyPC
	 * 
	 */
	private class SearchCustomerListTask
			extends
				AsyncTask<Object, Object, List<CustomerDetail>> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerActivityAudit.this);
				pd.setMessage("查询中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected List<CustomerDetail> doInBackground(Object... arg0) {
			List<CustomerDetail> reList = null;
			try {
				if (null != arg0 && arg0.length > 0) {
					reList = CustomerServiceProxy.getInstance(
							CustomerActivityAudit.this).CustomerExamineQuery(
							(ExamineQuery) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return reList;
		}

		@Override
		protected void onPostExecute(List<CustomerDetail> result) {
			super.onPostExecute(result);
			pd.cancel();
			listResult.setAdapter(null);
			if (result != null && result.size() > 0) {
				mCustomerDetailAdapter = new CustomerDetailAdapter(
						getApplicationContext(), result,
						layout.item_customer_audit_list);
				listResult.setAdapter(mCustomerDetailAdapter);
			} else {
				Toast.makeText(getApplicationContext(), R.string.no_results,
						Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 归属信息查询
	 * 
	 * @author MyPC
	 * 
	 */
	private class SearchAttributionListTask
			extends
				AsyncTask<Object, Object, List<CustomerAttribution>> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerActivityAudit.this);
				pd.setMessage("查询中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected List<CustomerAttribution> doInBackground(Object... arg0) {
			List<CustomerAttribution> reList = null;
			try {
				if (null != arg0 && arg0.length > 0) {
					reList = CustomerServiceProxy.getInstance(
							CustomerActivityAudit.this)
							.AttributionExamineQuery((ExamineQuery) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return reList;
		}

		@Override
		protected void onPostExecute(List<CustomerAttribution> result) {
			super.onPostExecute(result);
			pd.cancel();
			listResult.setAdapter(null);
			if (result != null && result.size() > 0) {
				mAttributionAdapter = new AttributionAdapter(
						getApplicationContext(), result,
						layout.item_customer_record_list);
				listResult.setAdapter(mAttributionAdapter);
			} else {
				Toast.makeText(getApplicationContext(), R.string.no_results,
						Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 客户审核异步类
	 * 
	 * @author MyPC
	 * 
	 */
	private class CustomerAuditTask extends AsyncTask<Object, Object, Boolean> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerActivityAudit.this);
				pd.setMessage("提交中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected Boolean doInBackground(Object... arg0) {
			boolean result = false;
			try {
				if (null != arg0 && arg0.length > 0) {
					result = CustomerServiceProxy.getInstance(
							CustomerActivityAudit.this).CustomerAudit(
							(CustomerExamine) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pd.cancel();
			if (result) {
				mCustomerDetailAdapter.setChangeState(mCustomerExamine);
				Toast.makeText(getApplicationContext(), "操作成功",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "操作失败",
						Toast.LENGTH_SHORT).show();
			}

		}
	}

	/**
	 * 归属记录审核异步类
	 * 
	 * @author MyPC
	 * 
	 */
	private class RecordAuditTask extends AsyncTask<Object, Object, Boolean> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerActivityAudit.this);
				pd.setMessage("提交中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected Boolean doInBackground(Object... arg0) {
			boolean result = false;
			try {
				if (null != arg0 && arg0.length > 0) {
					result = CustomerServiceProxy.getInstance(
							CustomerActivityAudit.this).RecordAudit(
							(AttributionExamine) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pd.cancel();
			if (result) {
				mAttributionAdapter.setChangeState(mAttributionExamine);
				Toast.makeText(getApplicationContext(), "操作成功",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "操作失败",
						Toast.LENGTH_SHORT).show();
			}

		}
	}

	public class AttributionAdapter extends BaseAdapter {
		private List<CustomerAttribution> mAttributionList = null;
		private Context mContext;
		private int mLayout;
		private LayoutInflater mInflater;

		public AttributionAdapter(Context context,
				List<CustomerAttribution> list, int layoutId) {
			mAttributionList = list;
			mContext = context;
			mLayout = layoutId;
			mInflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			if (mAttributionList != null) {
				return mAttributionList.size();
			} else {
				return 0;
			}
		}

		/**
		 * 审核一个客户，更新list中的状态
		 * 
		 * @param mCustomerExamine
		 */
		public void setChangeState(AttributionExamine attributionExamine) {
			List<CustomerAttribution> list = new ArrayList<CustomerAttribution>();
			for (CustomerAttribution model : mAttributionList) {
				if (model.AttributionID
						.equals(attributionExamine.AttributionID)) {
					model.AttributionState = attributionExamine.AttributionState;
					list.add(model);
					break;
				}
			}
			mAttributionList.removeAll(list);
			notifyDataSetChanged();
		}

		@Override
		public Object getItem(int position) {
			if (mAttributionList != null) {
				return mAttributionList.get(position);
			}
			return null;
		}

		public void setCustomerList(List<CustomerAttribution> list) {
			mAttributionList = list;
			notifyDataSetChanged();
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = mInflater.inflate(mLayout, null);
				viewHolder.tvCustomerName = (TextView) convertView
						.findViewById(id.tv_customer_name);
				viewHolder.tvStatus = (TextView) convertView
						.findViewById(id.tv_status);
				viewHolder.tvSubmitTime = (TextView) convertView
						.findViewById(id.tv_submit_time);
				viewHolder.tvRecordMsg = (TextView) convertView
						.findViewById(id.tv_record_msg);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			final CustomerAttribution cAttribution = mAttributionList
					.get(position);

			viewHolder.tvCustomerName.setText(cAttribution.CustomerName);
			viewHolder.tvRecordMsg.setText(cAttribution.AttributionMsg);
			if (("0").equals(cAttribution.AttributionState)) {
				viewHolder.tvStatus.setText(getResources().getString(
						R.string.status_1));
			} else if (("1").equals(cAttribution.AttributionState)) {
				viewHolder.tvStatus.setText(getResources().getString(
						R.string.status_2));
			} else {
				viewHolder.tvStatus.setText(getResources().getString(
						R.string.status_3));
			}

			// 3不能都能查看，绑定点击事件
			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mAttributionExamine = new AttributionExamine();
					mAttributionExamine.AttributionID = cAttribution.AttributionID;
					mAttributionExamine.ExamineUser = User.getInstance(
							getApplicationContext()).getUserNum();
					AlertDialog.Builder builder = new AlertDialog.Builder(
							CustomerActivityAudit.this);
					builder.setTitle(string.customer_audit_dialog_title)
							.setPositiveButton("通过",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											mAttributionExamine.AttributionState = "2";
											RecordAuditTask task = new RecordAuditTask();
											task.execute(mAttributionExamine);
										}
									})
							.setNegativeButton("未通过",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											mAttributionExamine.AttributionState = "1";
											RecordAuditTask task = new RecordAuditTask();
											task.execute(mAttributionExamine);
										}
									}).show();
				}
			});

			convertView.setTag(viewHolder);
			return convertView;
		}

		public class ViewHolder {
			public ImageView ivStatus;
			public TextView tvCustomerName;
			public TextView tvSubmitTime;
			public TextView tvRecordMsg;
			public TextView tvStatus;

		}
	}

	public class CustomerDetailAdapter extends BaseAdapter {
		private List<CustomerDetail> mCustomerList = null;
		private Context mContext;
		private int mLayout;
		private LayoutInflater mInflater;

		public CustomerDetailAdapter(Context context,
				List<CustomerDetail> list, int layoutId) {
			mCustomerList = list;
			mContext = context;
			mLayout = layoutId;
			// mInflater = LayoutInflater.from(mContext).inflate(layoutId,
			// null);
			mInflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			if (mCustomerList != null) {
				return mCustomerList.size();
			} else {
				return 0;
			}
		}

		/**
		 * 审核一个客户，更新list中的状态
		 * 
		 * @param customerExamine
		 */
		public void setChangeState(CustomerExamine customerExamine) {
			List<CustomerDetail> list = new ArrayList<CustomerDetail>();
			for (CustomerDetail customerDetail : mCustomerList) {
				if (customerDetail.CustomerID
						.equals(customerExamine.CustomerID)) {
					customerDetail.CustomerState = customerExamine.CustomerState;
					list.add(customerDetail);
					break;
				}
			}
			mCustomerList.removeAll(list);
			notifyDataSetChanged();
		}

		@Override
		public Object getItem(int position) {
			if (mCustomerList != null) {
				return mCustomerList.get(position);
			}
			return null;
		}

		public void setCustomerList(List<CustomerDetail> list) {
			mCustomerList = list;
			notifyDataSetChanged();
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				// convertView = LayoutInflater.from(mContext).inflate(mLayout,
				// null);
				convertView = mInflater.inflate(mLayout, null);
				viewHolder.tvCustomerName = (TextView) convertView
						.findViewById(id.tv_customer_name);
				viewHolder.tvStatus = (TextView) convertView
						.findViewById(id.tv_status);
				viewHolder.tvCustomerPhone = (TextView) convertView
						.findViewById(id.tv_customer_phone);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			final CustomerDetail cDetail = mCustomerList.get(position);

			viewHolder.tvCustomerName.setText(cDetail.CustomerName);
			viewHolder.tvCustomerPhone.setText(cDetail.CustomerPhone);
			if (("0").equals(cDetail.CustomerState)) {
				viewHolder.tvStatus.setText(getResources().getString(R.string.status_1));
			} else if (("1").equals(cDetail.CustomerState)) {
				viewHolder.tvStatus.setText(getResources().getString(R.string.status_2));
			} else {
				viewHolder.tvStatus.setText(getResources().getString(R.string.status_3));
			}

			// 3不能都能查看，绑定点击事件
			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mCustomerExamine = new CustomerExamine();
					mCustomerExamine.CustomerID = cDetail.CustomerID;
					AlertDialog.Builder builder = new AlertDialog.Builder(
							CustomerActivityAudit.this);
					final EditText etAdvise = new EditText(
							CustomerActivityAudit.this);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					lp.setMargins(10, 10, 10, 10);
					etAdvise.setLayoutParams(lp);
					builder.setTitle(string.customer_audit_dialog_title)
							.setView(etAdvise)
							.setPositiveButton("通过",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											mCustomerExamine.CustomerState = "2";
											mCustomerExamine.CustomerAdvise = etAdvise
													.getText().toString();
											CustomerAuditTask customerAuditTask = new CustomerAuditTask();
											customerAuditTask
													.execute(mCustomerExamine);
										}

									})
							.setNegativeButton("未通过",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											mCustomerExamine.CustomerState = "1";
											mCustomerExamine.CustomerAdvise = etAdvise
													.getText().toString();
											CustomerAuditTask customerAuditTask = new CustomerAuditTask();
											customerAuditTask
													.execute(mCustomerExamine);
										}
									}).show();

				}
			});

			// convertView.setTag(viewHolder);
			return convertView;
		}

		public class ViewHolder {
			public ImageView ivStatus;
			public TextView tvCustomerName;
			public TextView tvStatus;
			public TextView tvCustomerPhone;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			imgbtnHome.performClick();
		}
		return false;
	}

}
